import { ActionContext, ActionTree } from 'vuex';
import { Mutations } from './mutations';
import { State } from './state';
import { RootState } from '@/store';
import { getUserInfo, login } from '@/api/user';
import { storage } from '@/utils/Storage';
import { UserActionTypes, MutationType } from '@/enums/userEnums';
import router from '@/router';

type ActionAugments = Omit<ActionContext<State, RootState>, 'commit'> & {
    commit<K extends keyof Mutations>(key: K, payload: Parameters<Mutations[K]>[1]): ReturnType<Mutations[K]>;
};

type Actions = {
    [UserActionTypes.Login](context: ActionAugments, userInfo: any): Promise<any>;
    [UserActionTypes.GetInfo](context: ActionAugments): Promise<any>;
    [UserActionTypes.Logout](context: ActionAugments): Promise<any>;
};

export const actions: ActionTree<State, RootState> & Actions = {
    // 登录
    async [UserActionTypes.Login]({ commit }, userInfo) {
        try {
            const response: { [x: string]: any } = await login(userInfo);
            if (!response) return Promise.resolve(response);
            const {
                user: { user, roles },
                token,
            } = response;
            commit(MutationType.SetToken, token);
            commit(MutationType.SetInfo, user);
            commit(MutationType.SetRole, roles);
            commit(MutationType.SetName, user.username);
            return Promise.resolve(response);
        } catch (e) {
            return Promise.reject(e);
        }
    },

    // 获取用户信息
    [UserActionTypes.GetInfo]({ commit }) {
        return new Promise((resolve, reject) => {
            getUserInfo()
                .then((response) => {
                    const result = response;
                    resolve(response);
                })
                .catch(() => {
                    reject();
                });
        });
    },

    // 登出
    async [UserActionTypes.Logout]({ commit, state }) {
        storage.clear();
        commit(MutationType.SetInfo, {});
        commit(MutationType.SetToken, '');

        // storage.remove(MutationType.SetToken);

        const redirect = router.currentRoute.value.fullPath;
        const timer = window.setTimeout(() => {
            // router.replace({
            //     path: '/login',
            //     query: { redirect: redirect },
            // });
            window.location.reload;
            router.push('/login');
            clearTimeout(timer);
        }, 10);
        return Promise.resolve('');
    },
};
